<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员id" prop="vipId">
        <el-input
          v-model="queryParams.vipId"
          placeholder="请输入会员id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="理发师" prop="hairdresser">
        <el-select v-model="queryParams.hairdresser" placeholder="请选择理发师" clearable size="small">
          <el-option
            v-for="dict in hairdresserOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="助手" prop="assistant">
        <el-select v-model="queryParams.assistant" placeholder="请选择助手" clearable size="small">
          <el-option
            v-for="dict in assistantOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable size="small">
        <el-option
          v-for="dict in orderStatusOptions"
          :key="dict.dictValue"
          :label="dict.dictLabel"
          :value="dict.dictValue"
        ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="checkBoxDisable"  align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="会员id" align="center" prop="vipId" />
      <el-table-column label="折扣" align="center" prop="discount" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="理发师" align="center" prop="hairdresser" />
      <el-table-column label="助手" align="center" prop="assistant" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['order:order:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer">
    <el-button class="btn_pay"
      size="big"
      type="success"
      icon="el-icon-edit"
      @click="handlePayAdd()"
      v-hasPermi="['order:payment:add']"
    >付款</el-button>
      </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"  label-width="80px">
        <el-form-item label="会员id" prop="vipId">
          <el-input v-model="form.vipId" @change="changeDiscount" placeholder="请输入会员id" />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="form.productIds" @change="changeTotalPrice" multiple placeholder="请选择">
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input v-model="form.discount"  readonly="readonly" placeholder="请输入折扣" />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" readonly="readonly" placeholder="请输入总价" />
        </el-form-item>
        <el-form-item label="理发师" prop="hairdresser">
          <el-select v-model="form.hairdresser" placeholder="请选择理发师">
            <el-option
              v-for="dict in hairdresserOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="助手" prop="assistant">
          <el-select v-model="form.assistant" placeholder="请选择助手">
            <el-option
              v-for="dict in assistantOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请输入订单状态">
          <el-option
            v-for="dict in orderStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          >
          </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div  slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 添加或修改付款管理对话框 -->
    <el-dialog :title="payTitle" :visible.sync="payment" width="500px" append-to-body>
      <el-form ref="payForm" :model="payForm" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="payForm.orderId" readonly="readonly" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" readonly="readonly" placeholder="请输入总价" />
        </el-form-item>
        <el-form-item label="应收金额" prop="receivable">
          <el-input v-model="payForm.receivable" readonly="readonly"  placeholder="请输入应收金额" />
        </el-form-item>
        <el-form-item label="实收金额" prop="payment">
          <el-input v-model="payForm.payment" placeholder="请输入实收金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="payForm.payType" placeholder="请选择支付方式">
            <el-option
              v-for="dict in payTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收银员" prop="cashier">
          <el-select v-model="payForm.cashier" placeholder="请输入收银员" >
            <el-option
              v-for="dict in cashierOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="paySubmitForm">确 定</el-button>
        <el-button @click="payCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import { listOrder, getOrder, delOrder, addOrder, updateOrder, exportOrder } from "@/api/order/order";
import { getProduct }from "@/api/product/product";
import {addPayment} from "@/api/order/payment";
import {getVip, updateVip} from "@/api/vip/vip";

export default {
  name: "Order",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      orderList: [],
      //产品选择
      productOptions: [],
      //多个实现
      productIds:[],
      //理发师选择字典
      hairdresserOptions: [],
      //助手选择字典
      assistantOptions: [],
      //订单状态选择字典
      orderStatusOptions:[],
      //付款方式选择字典
      payTypeOptions:[],
      //收银员选择字典
      cashierOptions:[],
      // 弹出层标题
      title: "",
      // 付款弹出层标题
      payTitle: "",
      // 是否显示弹出层
      open: false,
      payment:false,
      //默认订单状态
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vipId: null,
        discount: null,
        totalPrice: null,
        hairdresser: null,
        assistant: null,
        orderStatus: null,
      },
      // 表单参数
      form: {
        orderStatus:'未付款',
      },
      //付款表单参数
      payForm:{},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("hairdresser").then(response => {
      this.hairdresserOptions = response.data;
    });
    this.getDicts("assistant").then(response => {
      this.assistantOptions = response.data;
    });
    this.getDicts("orderStatus").then(response => {
      this.orderStatusOptions = response.data;
    });
    this.getDicts("payType").then(response => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("cashier").then(response => {
      this.cashierOptions = response.data;
    });
  },
  methods: {
    changeDiscount() {
      if(this.form.vipId==1){
        this.form.discount=1;
      }else{
        this.form.discount=0.7
      }
    },
    changeTotalPrice() {
      this.form.totalPrice=0;
      for(var i=0;i<this.form.productIds.length;i++){
       getProduct(this.form.productIds[i]).then(response=>{
         this.form.totalPrice+=response.data.productPrice;
       })
      }
    },
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 付款取消按钮
    payCancel() {
      this.payment = false;
      this.payReset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: undefined,
        vipId: undefined,
        discount: undefined,
        totalPrice: undefined,
        hairdresser: undefined,
        assistant: undefined,
        orderStatus: undefined,
        createTime: undefined,
        productIds: []
      };
      this.resetForm("form");
    },

    payReset() {
      this.payForm = {
        paymentId: undefined,
        orderId: undefined,
        receivable: undefined,
        payment: undefined,
        payType: undefined,
        cashier: undefined,
        createTime: undefined,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getOrder().then(response => {
        this.productOptions = response.products;
        this.form.orderStatus='未付款';
        this.open = true;
        this.title = "添加订单管理";
      });
    },

    /** 新增付款操作 */
    handlePayAdd() {
      this.reset();
      const orderId = this.ids;
      getOrder(orderId).then(response => {
        this.form.totalPrice=response.data.totalPrice;
        this.payForm.orderId = response.data.orderId;
        this.payForm.receivable=response.data.totalPrice*response.data.discount;
        this.payForm.receivable=this.payForm.receivable.toFixed(1);
        this.payment = true;
        this.payTitle = "订单付款";
      });

      },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data;
        this.productOptions = response.products;
        this.form.productIds = response.productIds;
        this.open = true;
        this.title = "修改订单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        getVip(this.form.vipId).then(response=>{
         if(response.data==undefined){
           this.msgError("会员Id错误,请输入正确的会员Id!")
         }else{
           if (valid) {
             if (this.form.orderId != undefined) {
               updateOrder(this.form).then(response => {
                 this.msgSuccess("修改成功");
                 this.open = false;
                 this.getList();
               });
             } else {
               addOrder(this.form).then(response => {
                 console.log(this.form.orderId);
                 console.log(this.form.productIds);
                 this.msgSuccess("新增成功");
                 this.open = false;
                 this.getList();
               });
             }
           }
         }
        });

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$confirm('是否确认删除订单管理编号为"' + orderIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delOrder(orderIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有订单管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },


    /** 付款提交按钮 */
    paySubmitForm() {
      this.$refs["payForm"].validate(valid => {
         if (valid) {
           if(this.payForm.payType=="会员卡支付") {
             getOrder(this.payForm.orderId).then(response => {
               getVip(response.data.vipId).then(response => {
                 let pd = response.data.cardBalance - this.payForm.payment;
                 if(pd>=0){
                   response.data.cardBalance=pd;
                   updateVip(response.data);
                   addPayment(this.payForm).then(response => {
                     getOrder(this.payForm.orderId).then(response=>{
                       this.form=response.data;
                       this.form.orderStatus="已付款";
                       this.productOptions = response.products;
                       this.form.productIds = response.productIds;
                       updateOrder(this.form);
                       this.getList();
                     });
                     this.msgSuccess("新增成功");
                     this.payment = false;
                   });
                 }else{
                   this.msgError("卡余额不足,请及时充值");
                 }
               })
             })
           }else {
                 addPayment(this.payForm).then(response => {
                   getOrder(this.payForm.orderId).then(response=>{
                     this.form=response.data;
                     this.form.orderStatus="已付款";
                     this.productOptions = response.products;
                     this.form.productIds = response.productIds;
                     updateOrder(this.form);
                     this.getList();
                   });
                   this.msgSuccess("新增成功");
                   this.payment = false;
                 })};
               }
             })
           },

              // 检查是否禁用选择框
              checkBoxDisable(row){
                if(row.orderStatus=="未付款"){
                  return true;
                }else{
                  return false;
                }
              }
          }
          }
</script>
<style>
      .btn_pay {
        position: relative;
        margin: 20px;
        left: 90%;
      }
</style>
